<template>
    <div id="system">
      <Alert type="success">此页面仅站点创始人可见</Alert>
      <Card :dis-hover="true">
        <Form ref="form_data" :model="form_data">
          <FormItem label="是否开启主域名保护(域名防封)" prop="kuyuan_defend">
            <i-switch v-model="form_data.kuyuan_defend" @on-change="defendChange" />
          </FormItem>
          <FormItem label="后台是否显示公告" prop="notice_show">
            <i-switch v-model="form_data.notice_show" />
          </FormItem>
          <FormItem label="管理后台公告" prop="notice">
            <br />
            <Editor v-model="form_data.notice"></Editor>
          </FormItem>
          <FormItem>
            <Button type="primary" @click="submit('form_data')">确定</Button>
          </FormItem>
        </Form>
      </Card>
    </div>
</template>

<script>
import Editor from '@/components/editor'
export default {
  name: 'system',
  data () {
    return {
      form_data: {
        kuyuan_defend: false,
        notice: '',
        notice_show: false
      }
    }
  },
  components: {
    Editor
  },
  computed: {
    data () {
      let { kuyuan_defend, notice_show, notice } = this.form_data
      let data = {
        kuyuan_defend: kuyuan_defend ? '1' : '0',
        notice,
        notice_show: notice_show ? '1' : '0'
      }
      return data
    }
  },
  mounted () {
    this.find()
  },
  methods: {
    find () {
      this.$get('system/find')
        .then((res) => {
          let { code, data } = res.data
          if (code === 0) {
            let { kuyuan_defend, notice_show, notice } = data
            this.form_data = {
              kuyuan_defend: kuyuan_defend === '1',
              notice,
              notice_show: notice_show === '1'
            }
          }
        })
    },
    /**
     * 提交
     * @param name
     */
    submit (name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.$post('system/set', {
            data: this.data
          })
            .then((res) => {
              if (res.data.code === 0) {
                this.$Message.success('设置成功')
              } else {
                this.$Message.error('设置失败')
              }
            })
        }
      })
    },
    /**
     * 域名防封数据改变
     */
    defendChange (value) {
      if (value) {
        this.$get('system/testKuyuanDefend')
          .then((res) => {
            let { code, data } = res.data
            if (code === 0) {
              if (data === 0) {
                this.form_data.kuyuan_defend = false
                this.$Message.error({
                  content: '请先前往微擎商城安装我们的免费模块“酷源防封”',
                  duration: 3
                })
              }
            }
          })
      }
    }
  }
}
</script>
